import axios from 'axios'
import qs from 'qs'
import { Toast } from 'vant'
// import router from '../router'
import Vue from 'vue'
const bus = new Vue()
// 创建一个实例
const request = axios.create({
  baseURL: '/circle',
  timeout: 5000
})

// Add a request interceptor
request.interceptors.request.use(function (config) {
  // 请求时让loading显示
  bus.$showLoading()
  // Do something before request is sent
  if (config.url === '/shop/goods/list' && config.method === 'post') {
    config.data = qs.stringify(config.data)
  }
  // 请求头中 传access_token
  // 请求的所有信息
  const accessToken = localStorage.getItem('access_token')
  config.headers.access_token = accessToken
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})
/*
token如果过期 前台请求，需要toke的接口
后台 一般会返回一个 错误code
data: {
  code: 401,
  msg: 'token过期了，请重新登录'
}
*/
// Add a response interceptor
request.interceptors.response.use(function (res) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  // console.log(response);
  // 请求成功loading隐藏
  bus.$hideLoading()
  // 响应的所有信息
  // console.log(res.data.code)
  if (res.data.code === 401) {
    Toast('登录已过期,请重新登陆')
    bus.$router.push('/login')
  }
  return res
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  return Promise.reject(error)
})

export default request
